package com.harmony.pilot.agent.service;

import com.harmony.pilot.agent.model.ConversationContext;
import com.harmony.pilot.agent.model.Intent;
import com.harmony.pilot.llm.service.LLMService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Map;

import java.util.regex.Pattern;

@Service
@Slf4j
public class IntentAnalyzer {
    
    private final LLMService llmService;
    
    // 意图识别模式
    private static final Pattern CODE_GENERATION_PATTERN = 
        Pattern.compile("(生成|创建|实现|写|编写).*代码");
    private static final Pattern TEST_GENERATION_PATTERN = 
        Pattern.compile("(生成|创建|写).*(测试|单元测试|fuzz|UT)");
    private static final Pattern CODE_REVIEW_PATTERN = 
        Pattern.compile("(审查|检查|review|分析).*代码");
    private static final Pattern GIT_COMMIT_PATTERN = 
        Pattern.compile("(提交|commit|push).*代码");
    private static final Pattern OH_API_PATTERN = 
        Pattern.compile("(调用|使用|查找).*(包管理|samgr|系统能力|分布式|OpenHarmony).*(能力|api|功能)");
    
    public IntentAnalyzer(@Autowired(required = false) LLMService llmService) {
        this.llmService = llmService;
    }
    
    public Intent analyze(String userMessage, ConversationContext context) {
        // 1. 使用规则匹配进行快速识别
        Intent intent = ruleBasedAnalysis(userMessage);
        
        // 2. 使用LLM进行精确分析（如果规则匹配置信度较低）
        if (intent.getConfidence() < 0.7 && llmService != null) {
            Intent llmIntent = llmBasedAnalysis(userMessage, context);
            if (llmIntent.getConfidence() > intent.getConfidence()) {
                intent = llmIntent;
            }
        }
        
        return intent;
    }
    
    private Intent ruleBasedAnalysis(String message) {
        String lowerMessage = message.toLowerCase();
        
        if (CODE_GENERATION_PATTERN.matcher(message).find()) {
            return Intent.builder()
                .type(Intent.IntentType.CODE_GENERATION)
                .action("generate")
                .confidence(0.8)
                .build();
        }
        
        if (TEST_GENERATION_PATTERN.matcher(message).find()) {
            return Intent.builder()
                .type(Intent.IntentType.TEST_GENERATION)
                .action("generate_test")
                .confidence(0.8)
                .build();
        }
        
        if (GIT_COMMIT_PATTERN.matcher(message).find()) {
            return Intent.builder()
                .type(Intent.IntentType.GIT_OPERATION)
                .action("commit")
                .confidence(0.8)
                .build();
        }
        
        if (CODE_REVIEW_PATTERN.matcher(message).find()) {
            return Intent.builder()
                .type(Intent.IntentType.CODE_REVIEW)
                .action("review")
                .confidence(0.8)
                .build();
        }
        
        if (OH_API_PATTERN.matcher(message).find()) {
            return Intent.builder()
                .type(Intent.IntentType.CODE_GENERATION)
                .action("openharmony_api")
                .confidence(0.9)
                .build();
        }
        
        return Intent.builder()
            .type(Intent.IntentType.GENERAL_QUERY)
            .confidence(0.5)
            .build();
    }
    
    private Intent llmBasedAnalysis(String message, ConversationContext context) {
        if (llmService == null) {
            return Intent.builder()
                .type(Intent.IntentType.GENERAL_QUERY)
                .confidence(0.5)
                .build();
        }
        
        try {
            String prompt = buildIntentAnalysisPrompt(message, context);
            com.harmony.pilot.common.dto.LLMRequest request = 
                com.harmony.pilot.common.dto.LLMRequest.builder()
                    .prompt(prompt)
                    .build();
            
            Map<String, Object> result = llmService.generate(request);
            if (result != null && result.containsKey("content")) {
                return parseIntentFromLLM(result.get("content").toString());
            }
        } catch (Exception e) {
            log.error("Failed to analyze intent with LLM", e);
        }
        
        return Intent.builder()
            .type(Intent.IntentType.GENERAL_QUERY)
            .confidence(0.5)
            .build();
    }
    
    private String buildIntentAnalysisPrompt(String message, ConversationContext context) {
        StringBuilder prompt = new StringBuilder();
        prompt.append("分析以下用户消息的意图，返回JSON格式：\n");
        prompt.append("用户消息：").append(message).append("\n\n");
        prompt.append("可用意图类型：\n");
        prompt.append("- CODE_GENERATION: 生成代码\n");
        prompt.append("- CODE_COMPLETION: 代码补全\n");
        prompt.append("- TEST_GENERATION: 生成测试\n");
        prompt.append("- CODE_REVIEW: 代码审查\n");
        prompt.append("- GIT_OPERATION: Git操作\n");
        prompt.append("\n返回格式：\n");
        prompt.append("{\"type\": \"意图类型\", \"action\": \"具体动作\", \"confidence\": 0.9}\n");
        return prompt.toString();
    }
    
    private Intent parseIntentFromLLM(String response) {
        // 解析LLM返回的JSON
        // 这里简化处理，实际应该使用JSON解析器
        try {
            // TODO: 使用Jackson或Gson解析
            return Intent.builder()
                .type(Intent.IntentType.GENERAL_QUERY)
                .confidence(0.7)
                .build();
        } catch (Exception e) {
            log.error("Failed to parse intent from LLM", e);
            return Intent.builder()
                .type(Intent.IntentType.GENERAL_QUERY)
                .confidence(0.5)
                .build();
        }
    }
}

